package util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import support.ScanningFile;
import support.anno.Config;

import java.io.File;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

//主要用于扫描带有RemoteClass的类
public class AnnotaionScanner {
    static Logger logger = LoggerFactory.getLogger(AnnotaionScanner.class);

    //废弃，不能扫描jar包中的类。。。应用打成jar包后就无效了，只在编译环境下有效
    static public synchronized List<String> scanner(String path,Class anno){
        classNames.clear();
        classPaths.clear();
        String basePack = path;
//        String classpath = AnnotaionScanner.class.getResource("/").getPath();
        String classpath = AnnotaionScanner.class.getClassLoader().getResource("").getPath();
        logger.info("------{}",classpath);
        basePack = basePack.replace(".", "/");
        //然后把classpath和basePack合并
        String searchPath = classpath + basePack;
        doPath(new File(searchPath));

        classPaths.forEach(s->{
            s = s.replace(classpath.replace("/","\\").replaceFirst("\\\\",""),"").replace("\\",".").replace(".class","");
            if(check(s,anno)) classNames.add(s);
        });

        return classNames;
    }

    //支持2种扫描模式
    static public synchronized List<String> scanner2(String basePack,Class anno){
        ScanningFile scanningFile=new ScanningFile();
        List<String> res = new ArrayList<>();
        List<String> scanner = scanningFile.scanner(basePack);
        scanner.forEach(c->{
            if(check(c,anno)) res.add(c);
        });
        return res;
    }

    public static void main(String[] args) {
        List<String> list = scanner2("support", Config.class);
        System.out.println(list);
    }

    static List<String> classPaths = new ArrayList<>();
    static List<String> classNames = new ArrayList<>();
//    public static void main(String[] args) {
//        List server = scanner("server", RemoteClass.class);
//        System.out.println(server);
//    }

    private static boolean check(String className,Class anno){
        try {
            Class<?> aClass = Class.forName(className);
            Annotation annotation = aClass.getAnnotation(anno);
            return annotation!=null;

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }

    }

    private static void doPath(File file) {
        if (file.isDirectory()) {//文件夹
            //文件夹我们就递归
            File[] files = file.listFiles();
            for (File f1 : files) {
                doPath(f1);
            }
        } else {//标准文件
            //标准文件我们就判断是否是class文件
            if (file.getName().endsWith(".class")) {
                //如果是class文件我们就放入我们的集合中。
                classPaths.add(file.getPath());
            }
        }
    }
}
